﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Reflexive.IO
{

    public class Subscription<T> : IObserver<T>, IDisposable
    {
        IObserver<T> _observer;
        public event EventHandler<IObserver<T>> UnSubscribe;

        public Subscription(IObserver<T> observer)
        {
            _observer = observer;
        }

        public void Dispose()
        {
            if (UnSubscribe != null)
            {
                UnSubscribe.BeginInvoke(this, this._observer, delegate(IAsyncResult result)
                {
                    ((EventHandler<IObserver<T>>)((AsyncResult)result).AsyncDelegate).EndInvoke(result);

                }, null);
            }
        }

        public void OnCompleted()
        {
            _observer.OnCompleted();
        }

        public void OnError(Exception error)
        {
            _observer.OnError(error);
        }

        public void OnNext(T value)
        {
            _observer.OnNext(value);
        }
    }
}
